/**
 * 相关终端设备弹框详情
 */
Vue.component('dp-mark-dialog', {
    template: `
    <el-dialog  :title="param.terminal_name||param.terminalName||'终端详情'" class="dp-mark-dialog__wrapper" custom-class="dp-mark-dialog" :visible.sync="dialogShow" width="52%" append-to-body>
        <div class="device-dialog-info">
            <p v-for="(item, index) in terminalInfoList" :key="index">{{item.label}}：<span :title="item.value">{{item.value}}</span></p>
        </div>
       <component :is="curComp" v-bind="param" v-if="dialogShow"></component>
    </el-dialog>`,

    props: {
        visible: {type: Boolean, default: true},
        terminalType: {type: [Number, String]},     // 终端类型
        terminalId: {type: [Number, String]},       // 终端id
        terminalSerial: {type: [String]},           // 终端序列号
        param: {type: Object, default: () => ({})}  // 相关参数
    },

    data() {
        return {
            dialogShow: false,
        }
    },

    computed: {

        // 设备序列号
        terminalSerial() {
            return this.param.terminalSerial || this.param.terminal_serial
        },

        // 当前使用的弹框组件
        curComp() {
            const enums = [
                {type: '虫情终端', value: [1], comp: 'dp-mark-dialog-insect'},
                // {type: '气象站', value: [20, 52, 57, 63], comp: 'dp-mark-dialog-qxz'},
                {type: '墒情', value: [20, 52, 57, 63, 35], comp: 'dp-mark-dialog-sq'},
                {type: '摄像头', value: [40]},
                {type: '控制柜', value: [33]},
            ];
            const t = Number(this.terminalType) || Number(this.param.terminalType) || Number(this.param.terminal_type)
            if (!t) return null;
            const {comp = null} = enums.find(item => item.value.includes(t)) || {};
            return comp;
        },
        // 当前终端的详情
        terminalInfoList() {
            let list = [
                {label: '设备序列号', value: '--', key: 'terminal_serial'},
                {label: '设备状态', value: '--', key: 'online'},
                {label: '生产企业', value: '浙江托普云农科技股份有限公司'},
                {label: '经纬度', value: '--', key: 'coordinates'}
            ];
            const {terminal_serial, terminalSerial = '', online, longitude = '', latitude = '', terminal_name} = this.param;
            list.forEach(item => {
                const {key} = item;
                switch (key) {
                    case 'terminal_serial' :
                        item.value = terminal_serial || terminalSerial || '--';
                        break;
                    case 'online' :
                        item.value = online == 1 ? '在线' : '离线';
                        break;
                    case 'coordinates' :
                        if (longitude && latitude) {
                            item.value = `${longitude},${latitude}`
                        }
                        break;
                }
            })
            return list;
        },
    },

    watch: {
        visible: {
            handler(v) {
                if (v) {
                    this.dialogShow = v;
                }
            }
        },

        dialogShow: {
            handler(v) {
                this.$emit('update:visible', v)
            }
        }
    }
})


/**虫情相关弹框**/
Vue.component('dp-mark-dialog-insect', {
    template: `
    <div class="dp-mark-dialog__type dp-mark-dialog-insect">
        <dp-dialog-section title="实时数据" >
            <template #search>
                <el-date-picker  @change="dateRangeChange" :clearable="false" style="width: 300px;" size="mini" v-model="searchData.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
            </template>
            <top-chart-line :option="option_chart" v-if="option_chart" height="30vh"></top-chart-line>
            <dp-no-data v-else height="30vh"></dp-no-data>
        </dp-dialog-section>
       
        <dp-dialog-section title="图像列表" height="15vmin">
            <dp-swiper :list="swiperData.list" v-if="swiperData.list.length">
                <div class="insect-siper-item" slot-scope="{ item }">
                     <div class="insect-swiper-item__pic">
                        <el-image style="width: 100%; height: 100%;" :src="item.img_url" fit="fill"></el-image>
                        <div class="create-time">{{item.create_time}}</div>
                     </div>
                     <div class="insect-swiper-item__info">
                        <span class="info-num">虫子{{item.num}}头</span>
                        <span class="info-more" @click="openDetails(item)" v-show="item.num>0">详情>></span>
                     </div>
                </div>
            </dp-swiper>
            <dp-no-data v-else></dp-no-data>
            <el-dialog title="详情" class="dp-mark-dialog__wrapper" custom-class="dp-mark-dialog"  :visible.sync="detailsData.visible" width="52%" append-to-body>
                 <div class="konva-container" style="height:760px;" v-loading="detailsData.loading"></div>
                 <div class="legend-list-konvas">    
                     <div class="li-item" v-for="item of detailsData.legendList">
                        <div class="dot" :style="{background:item.bgColor}"></div>
                        <span>{{item.insect_name}}</span> <span>{{item.number}}头</span>
                     </div>
                </div>
            </el-dialog>
        </dp-dialog-section> 
    </div>`,

    props: {
        terminal_serial: {type: String},   // 终端序列号
    },

    data() {
        return {
            searchData: {
                dateRange: [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
            },
            pickerOptions: '',
            chartData: {
                list: [],
            },
            swiperData: {
                list: [],
                total: 0,
                page: 1,
                size: 20,
            },

            detailsData: {
                stage: null,
                layer: null,
                group: null,
                scale: 1,
                visible: false,
                legendList: [],
                loading: false
            },

        }
    },

    computed: {
        option_chart() {
            if (!this.chartData.list.length) return null;
            const xAxisData = this.chartData.list[0].data.map(item => dayjs(item.x).format('YYYY-MM-DD'));
            let legendData = [];
            let series = [];

            this.chartData.list.forEach(item => {
                series.push({
                    name: item.name,
                    data: item.data.map(ele => ele.y.toFixed(0)),
                })
                legendData.push(item.name)
            })

            return {
                grid: {bottom: 38},
                yAxis: {
                    minInterval: 1,
                },
                xAxisData,
                series: series,
                legend: {
                    data: legendData,
                    bottom: 0,
                    left: 'center',
                },

                /*todo 考虑下很多项的情况*/
                tooltip: {
                    appendToBody: true,
                    formatter: (param) => {
                        html = `<div style="margin-bottom:6px;">${param[0].name}</div>`;
                        param.filter(item => item.value != 0).forEach((item, idx) => {
                            const unit = '头';
                            html += `${item.marker} <span style="line-height:2;">${item.seriesName}：${item.value}${unit || ""}</span> <br />`;
                        })
                        return html;
                    }
                }
            }
        },
        option_swiper() {
            return {
                slidesPerGroup: 1,      // 滚动分组
                // speed: 1200
            }
        },
    },

    watch: {
        terminal_serial: {
            handler(num) {
                if (num) {
                    this.getCqCurvData()
                    this.getCqImgList();
                }
            },
            immediate: true
        }
    },

    methods: {
        /**
         * 点击打开详情
         * @param item
         */
        openDetails(item) {
            this.detailsData.visible = true;
            this.$nextTick(() => {
                this.initKonva(item);
            })
        },

        // 初始化konva
        async initKonva(item) {
            let dom = 'konva-container';
            const konva_width = document.querySelector(`.${dom}`).offsetWidth;
            const konva_height = document.querySelector(`.${dom}`).offsetHeight;
            this.detailsData.stage = new Konva.Stage({container: `.${dom}`, width: konva_width, height: konva_height});
            this.detailsData.layer = new Konva.Layer();
            this.detailsData.stage.add(this.detailsData.layer);
            this.detailsData.loading = true;
            const {width, height, img} = await loadImage(item.orignal_url);
            this.detailsData.loading = false;
            const ratio = width / height;
            const scale = konva_width / width;
            this.detailsData.scale = scale;
            const imgNode_width = konva_width; //宽度固定写死，宽度更具计算得到
            const imgNode_height = imgNode_width / ratio;

            // 创建组
            const group = new Konva.Group({
                draggable: false,
                name: 'group',
                x: (konva_width - imgNode_width) / 2,   // 默认居中位置
                y: (konva_height - imgNode_height) / 2,   // 默认居中位置,
                width: width,
                height: height,
                scaleX: scale,
                scaleY: scale,
            });

            // 创建图片元素
            const imgNode = new Konva.Image({
                draggable: false,
                x: 0,
                y: 0,
                id: 'imgNode',
                width: width,
                height: height,
                image: img,
            })
            group.add(imgNode);
            this.detailsData.group = group;
            this.detailsData.layer.add(group);
            this.detailsData.layer.draw();
            this.getinsectMark(item.img_id)
        },

        // 添加虫子标记层
        addMaskLayer(list) {
            list.forEach((item, index) => {
                const {position = [], count, type, bgColor} = item || {};
                console.log(bgColor)
                if (position && position.length > 0) {
                    position.forEach((ele, i) => {
                        const {rb, lt} = ele;
                        const [x1, y1] = lt.split(',');
                        const [x2, y2] = rb.split(',');
                        const width = x2 - x1;
                        const height = y2 - y1;
                        const poly = new Konva.Rect({
                            x: x1,
                            y: y1,
                            width: width,
                            height: height,
                            fill: bgColor + '20',
                            stroke: bgColor,
                            strokeWidth: 2,
                            strokeScaleEnabled: false,
                            dashEnabled: true,
                            dash: [5, 5]
                        });

                        const text = new Konva.Text({
                            x: x1,
                            y: y1,
                            width: width,
                            height: height,
                            text: i + 1,
                            fontSize: 15 / this.detailsData.scale,
                            fill: '#fff',
                            align: 'center',
                            verticalAlign: 'middle',
                        });

                        this.detailsData.group.add(poly);
                        this.detailsData.group.add(text);
                        this.detailsData.layer.add(this.detailsData.group);
                        this.detailsData.layer.draw();
                    })
                }
            })
        },

        // 获取虫子标记数据
        async getinsectMark(imgId) {
            const data = await requestApi('getCqImageDetail', {
                serialNums: this.terminal_serial,
                imgId: imgId,
            });
            const {cnts = []} = data || {};
            const list = cnts.map(item => {
                return {
                    bgColor: item.type_obj.color,
                    insect_name: item.type_obj.insect_name,
                    position: item.square ? JSON.parse(item.square) : [],
                    number: item.number
                }
            })
            this.detailsData.legendList = list;
            this.addMaskLayer(list);
        },

        dateRangeChange() {
            this.chartData.list = [];
            this.swiperData.list = [];
            this.getCqCurvData();
            this.getCqImgList();
        },

        /**
         * 获取虫害的相关图表数据
         */
        async getCqCurvData() {
            const [startDate, endDate] = this.searchData.dateRange || ['', ''];
            const data = await requestApi('getCqCurvData', {
                serialNums: this.terminal_serial,
                insectType: '',
                subStatType: 2,
                statType: 5,
                startDate: startDate,
                endDate: endDate
            });
            this.chartData.list = data;
        },

        /**
         * 获取虫害的图片数据
         */
        async getCqImgList() {
            const [startDate, endDate] = this.searchData.dateRange || ['', ''];
            const data = await requestApi('getCqImgList', {
                serialNum: this.terminal_serial,
                startDate: startDate,
                endDate: endDate,
                insectTypes: "",
                page: 1,
                size: 100,
                desc: 1
            });
            let {total, list} = data || {};

            if (list && list.length) {
                list.forEach(item => {
                    if (item.insect_info && item.insect_info.length) {
                        item.num = item.insect_info.reduce((sum, item) => sum + item.number, 0)
                    } else {
                        item.num = 0;
                    }
                })
                this.swiperData.list = list;
            }
        },
    }
})

/**墒情相关弹框**/
Vue.component('dp-mark-dialog-sq', {
    template: `
    <div class="dp-mark-dialog__type dp-mark-dialog-sq">
        <dp-dialog-section title="实时数据">
            <template #search>
                <el-radio-group class="dialog-radio-group" @change="sensorClassifyChange" v-model="sensorData.curClassify" size="mini">
                    <el-radio-button :label="item.value" v-for="item of sensorData.classify">{{item.label}}</el-radio-button>
                </el-radio-group>
            </template>
            <dp-swiper :list="sensorData.list" :option="option_swiper" v-if="sensorData.list.length">
                <div class="sensor-siper-item" slot-scope="{ item }">
                     <div class="sensor-siper-item__value">
                        <div class="sensor-value">{{sensorValue(item)}}</div>
                        <div class="sensor-unit" v-show="item.sensor_type_id != 180">{{item.sensor_unit}}</div>
                     </div>
                     <div class="sensor-siper-item__info">
                        <div class="sensor-name">{{item.device_name}}</div>
                     </div>
                </div>
            </dp-swiper>
            
            <dp-no-data v-else></dp-no-data>
           
            <div class="sensor-chart-container">
                <div class="search-bar">    
                    <el-radio-group class="dialog-radio-group"  v-model="chartData.curTime" size="mini" @change="timeTypeChange">
                        <el-radio-button :label="item" v-for="item of chartData.timeTypes"></el-radio-button>
                    </el-radio-group>
                    <div class="date-range">
                        <el-date-picker @change="getsensorData" popper-class="dialog-date-picker-popper"  :disabled="chartData.curTime!=='自选'" :clearable="false" style="width: 300px;" size="mini" v-model="chartData.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                    </div>
                </div>
                <div class="chart-wraper">
                     <top-chart-line :option="option_chart" v-if="option_chart"></top-chart-line>
                     <dp-no-data v-else></dp-no-data>
                </div>
           </div>
        </dp-dialog-section>
      
    </div>`,

    props: {
        terminal_serial: {type: String},   // 终端序列号
    },

    data() {
        return {
            sensorData: {
                source: [],
                list: [],
                classify: [
                    {label: '全部', value: 0},
                    {label: '温湿度', value: 1},
                    {label: '土壤温度', value: 2},
                    {label: '土壤水分', value: 3},
                    {label: '其他', value: 4},
                ],
                curClassify: 0,
            },

            chartData: {
                timeTypes: ['天', '周', '月', '年', '自选'],
                curTime: '天',
                dateRange: [dayjs().subtract(1, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
                list: [],
                data_rows: [],
                device_id_sensor_map: {},

            },
            pickerOptions: '',
        }
    },

    computed: {
        option_chart() {
            if (!this.chartData.data_rows.length || !Object.keys(this.chartData.device_id_sensor_map).length) return null;
            const xAxisData = this.chartData.data_rows.map(item => dayjs(item.datetime).format('YYYY-MM-DD HH:mm'));
            let legendData = [];
            let series = [];

            for (const device_id in this.chartData.device_id_sensor_map) {
                const {unit, device_name, sensor_type_id} = this.chartData.device_id_sensor_map[device_id] || {};
                legendData.push(device_name);
                const seriesData = this.chartData.data_rows.map(item => {
                    const cur = item.sensor_data || {};
                    return cur[device_id] || null;
                })
                series.push({
                    type: 'line',
                    name: device_name,
                    data: seriesData,
                    symbol: 'none',
                    unit: unit,
                    sensor_type_id: sensor_type_id
                })
            }

            return {
                grid: {top: 40, bottom: 40, left: 30, right: 30},
                xAxisData,
                series: series,
                legend: {
                    data: legendData,
                    bottom: 0,
                    left: 'center',
                },

                /*todo 考虑下很多项的情况*/
                tooltip: {
                    appendToBody: true,
                    formatter: (param) => {
                        html = `<div style="margin-bottom:6px;">${param[0].name}</div>`;
                        param.filter(item => item.value != 0).forEach((item, idx) => {
                            const {unit, sensor_type_id} = series.find(ele => ele.name == item.seriesName) || {};

                            if (sensor_type_id != 180) {
                                html += `${item.marker} <span style="line-height:2;">${item.seriesName}：${item.value || '-'}${unit || ""}</span><br />`;
                            } else {
                                html += `${item.marker} <span style="line-height:2;">${item.seriesName}：${item.value || '-'}${unit || ""}</span><span>（${windDirection(item.value)}）</span> <br />`;
                            }

                        })
                        return html;
                    }
                }
            }
        },
        option_swiper() {
            return {
                slidesPerView: 5,
            }
        },
    },

    watch: {
        terminal_serial: {
            handler(num) {
                if (num) {
                    this.getSensorLastValue()
                    this.getsensorData();
                }
            },
            immediate: true
        }
    },

    methods: {
        /**
         * 土壤传感器分类单选切换
         */
        sensorClassifyChange(value) {
            if (value == 0) {
                this.sensorData.list = this.sensorData.source
            } else if (value == 1) {
                this.sensorData.list = this.sensorData.source.filter(item => item.device_name.indexOf("温度") != -1 || item.device_name.indexOf("湿度") != -1);
            } else if (value == 2) {
                this.sensorData.list = this.sensorData.source.filter(item => item.device_name.indexOf("土壤温度") != -1);
            } else if (value == 3) {
                this.sensorData.list = this.sensorData.source.filter(item => item.device_name.indexOf("土壤水分") != -1);
            } else if (value == 4) {
                this.sensorData.list = this.sensorData.source.filter(item => item.device_name.indexOf("土壤水分") == -1 && item.device_name.indexOf("土壤温度") == -1 && item.device_name.indexOf("温度") == -1 && item.device_name.indexOf("湿度") == -1);
            }
        },

        /**
         * 时间类型的切换
         */
        timeTypeChange(value) {
            switch (value) {
                case '天' :
                    this.chartData.dateRange = [dayjs().subtract(1, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')];
                    break;
                case '周' :
                    this.chartData.dateRange = [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')];
                    break;
                case '月' :
                    this.chartData.dateRange = [dayjs().subtract(1, 'month').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')];
                    break;
                case '年' :
                    this.chartData.dateRange = [dayjs().subtract(1, 'year').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')];
                    break;
                case '自选' :
                    break;
            }
            this.getsensorData();
        },

        /**
         * 获取传感器列表
         */
        async getSensorLastValue() {
            const data = await requestApi('getSensorLastValue', {serial_nums: this.terminal_serial});
            this.sensorData.list = data;
            this.sensorData.source = data;
        },

        /**
         * 获取传感器历史数据
         */
        async getsensorData() {
            const [startDate, endDate] = this.chartData.dateRange || ['', ''];
            const data = await requestApi('getSqCurvData', {
                serial_num: this.terminal_serial,
                start_date: startDate,
                end_date: endDate,
                period: "30",
                land_up_low: true
            });
            const {data_rows, device_id_sensor_map, warning_list, alert_list} = data || {};
            this.chartData.data_rows = data_rows || [];
            this.chartData.device_id_sensor_map = device_id_sensor_map || [];
            this.chartData.warning_list = warning_list || [];
            this.chartData.alert_list = alert_list || [];
        },
    }
})


/**弹框中区域组件**/
Vue.component('dp-dialog-section', {
    template: `
    <div class="dp-dialog-section">
        <div class="dialog-section__top">
            <div class="left">
                <div class="name">{{title}}</div>   
                <div class="search">
                    <slot name="search"></slot>
                </div>
            </div>
            <div class="right">
                <slot name="other"></slot>
            </div>
        </div>
         <div class="dialog-section__content" :style="content_style">
            <slot>
                <dp-no-data></dp-no-data>
            </slot>
         </div>
    </div>`,

    props: {
        title: {type: String, default: '标题'},
        height: {type: [String, Number], default: '25vmin'},
    },


    computed: {
        option_chart() {
            return null;
        },

        content_style() {
            return {
                // height: this.height
            }
        }
    }
})

/**
 * swiper封装
 */
Vue.component('dp-swiper', {
    template: `
        <div class="dp-swiper">
            <div class="swiper-btn-prev swiper-btn">
                <img src="../../resources/img/dp-mark-dialog/dialog-swiper-pre.png" alt="左按钮" v-show="showArrow">
            </div>
            <div class="swiper" :id="this.uuid">
                <div class="swiper-wrapper">
                    <div class="swiper-slide" v-for="(item, index) in list" :key="item.id || index">
                        <slot :item="item" :index="index"></slot>
                    </div>
                </div>
            </div>
            <div class="swiper-btn-next swiper-btn">
                <img src="../../resources/img/dp-mark-dialog/dialog-swiper-next.png" alt="右按钮" v-show="showArrow">
            </div>
        </div>
    `,
    props: {
        option: {type: Object, default: () => ({})},
        list: {type: Array, default: () => []}
    },
    data() {
        return {
            swiper: null,
            uuid: '',
        }
    },

    computed: {
        showArrow() {
            const slidesPerView = this.option.slidesPerView || 4;
            if (this.list.length > 0 && this.list.length > slidesPerView) {
                return true;
            }
            return false
        }
    },

    watch: {
        list: {
            handler(val) {
                this.$nextTick(() => {
                    this.swiper && this.swiper.update(true);
                })
            },
            deep: true
        },
    },
    methods: {
        initSwiper() {
            const option = {
                slidesPerView: 4,
                spaceBetween: 15,
                loop: false,
                navigation: {
                    nextEl: '.swiper-btn-next',
                    prevEl: '.swiper-btn-prev',
                },
                on: {
                    transitionStart: (swiper) => {
                        let index = swiper.activeIndex;
                        this.$emit("swiper-info", swiper);
                        this.$emit('swiper-index', index);
                    },
                    // 向前切换
                    slideNextTransitionStart: (swiper) => {
                        let index = swiper.activeIndex;
                        this.$emit('swiper-next', index, swiper);
                    },
                    // 拖动slide时执行
                    sliderMove: (swiper) => {
                        let index = swiper.activeIndex;
                        this.$emit('swiper-move', index, swiper);
                    },
                },
            }
            this.swiper = new Swiper(`#${this.uuid}`, {...option, ...this.option});
        },
    },
    created() {
        this.uuid = uuidGenerate('swiper_');
    },
    mounted() {
        this.$nextTick(() => {
            this.initSwiper();
        })
    },
});

/**
 * 生成唯一标识
 * @returns {string}
 */
function uuidGenerate(prefix) {
    let d = new Date().getTime();

    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }

    const uuid = 'xxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });

    return prefix + uuid.substring(0, 8);
}


/**
 * 如果为整数返回整数，如果为小数，保留两位小数点
 * @param value
 * @returns {number|*}
 */
function formatNumber(value) {
    if (!value) return '- -';
    const theValue = Number(value);
    if (Number.isInteger(theValue)) {
        return theValue;
    } else {
        return parseFloat(theValue.toFixed(2));
    }
}

/**
 * 设备图标
 * @param device
 */
function deviceIcon(device) {
    let sensorTypeId = device.sensorTypeId || device.sensor_type_id;
    if (sensorTypeId != undefined) {
        return 'tp-icon-sensor-' + sensorTypeId;
    }
}

/**
 * 传感器值
 * @param sensor
 * @returns {string}
 */
function sensorValue(sensor, key = 'device_value') {
    let {sensor_type_id, precision = 1, sensor_unit = ''} = sensor;
    let value = null;
    if (sensor[key] != undefined && !isNaN(sensor[key])) {
        if (sensor_type_id != 180) {
            value = parseFloat(sensor[key].toFixed(precision));
        } else {
            //风向特殊处理
            return windDirection(sensor[key]);
        }
    } else {
        value = '--';
    }
    return value;
}

/**
 * 根据偏转的角度判断风向（如东风、西北风等）
 * @param dtn
 * @returns {string}
 */
function windDirection(value) {
    let direction = '--';
    if (value != null && value != undefined && !isNaN(value)) {
        let dtn = parseFloat(value);
        if ((dtn >= 337.6 && dtn <= 360) || (dtn >= 0 && dtn <= 22.5)) {
            direction = '北风';
        } else if (dtn >= 22.6 && dtn <= 67.5) {
            direction = '东北风';
        } else if (dtn >= 67.6 && dtn <= 112.5) {
            direction = '东风';
        } else if (dtn >= 112.6 && dtn <= 157.5) {
            direction = '东南风';
        } else if (dtn >= 157.6 && dtn <= 202.5) {
            direction = '南风';
        } else if (dtn >= 202.6 && dtn <= 247.5) {
            direction = '西南风';
        } else if (dtn >= 247.6 && dtn <= 292.5) {
            direction = '西风';
        } else if (dtn >= 292.6 && dtn <= 337.5) {
            direction = '西北风';
        }
    }
    return direction;
}

/**
 * @descript: 图片加载完成后的操作
 * @param  {src}
 * @return {width} 图片实际宽度
 * @return {height} 图片实际高度
 * @return {img} 图片对象
 */
function loadImage(src) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = src;
        // img.crossOrigin = 'Anonymous'; // ios可能会报错
        img.onload = () => {
            resolve({
                width: img.width,
                height: img.height,
                img
            })
        };
        img.onerror = err => {
            reject(err)
        };
    })
}

/** 通用请求 **/
function request(api, param, method = 'post') {
    return new Promise((resolve, reject) => {
        tpHttp[method](this, `${api}`, {param: JSON.stringify(param || {})}, (data, code, message) => {
                const res = {data, code, message};
                if (code == 0) {
                    resolve(data);
                } else {
                    reject(res);
                }
            }
        );
    });
}

/** 公用api请求 **/
function requestApi(apiAlias, key) {
    const param = {
        apiAlias: apiAlias,
        key: Object.assign({where: '', orderBy: ''}, key),
    };
    return request(`action=com.top.scree.cq.callDcApiByAlias`, param);
}
